import { genUUID } from '../utils/utils';
let md5 = require('js-md5');
let mpMD5 = require('../utils/md5');
const config = require('config-lite')({
  filename: 'default',
  config_basedir: __dirname,
  config_dir: 'config',
});
const { cookiesConfig } = config;
const blankUrl = [
  '/api/adminCenter/logout',
  '/api/getSessionId',
  '/api/check/checkServer',
  '/api/client/login/getTmpQrcode',
  '/api/client/login/getSession',
  '/api/client/login/checkVersion',
  '/api/adminUser/queryCurrVersion',
  '/api/getSessionId',
  '/xkdata-web/wechatNotify',
  '/api/wxPublicAccount/syncSaveMedia',
  '/api/cssMediaChat/updateGetCloudToken',
  '/api/cssMediaChat/syncSaveMedia',
  '/api/cssMediaChat/queryMediaExited',
  '/api/tempStorage',
  '/xkdata-web/uPayOrder',
  '/xkdata-web/corp/order',
  '/api/tempStorage',
  '/mp/tmpMeedia/syncSaveMedia',
  '/api/uploadAndGetWxMediaId',
  '/api/mobile/uPayOrder/wxH5Pay',
  '/api/mobile/uPayOrder/wxGetSign',
  '/api/uPayOrder/getWxPayParams',
  '/api/uPayOrder/getWxPaySign',
  '/api/uPayOrder/wxCreateOrder',
  '/api/bargain/saveBargain',
  'api/companyAccount/getCodeParameter',
];
export async function SessionId(ctx, next) {
  let sessionId = ctx.cookies.get('sessionId');
  if (!sessionId) {
    sessionId = genUUID(32);
    ctx.cookies.set('sessionId', sessionId, cookiesConfig);
  } else {
    ctx.cookies.set('sessionId', sessionId, cookiesConfig);
  }
  ctx.sessionId = sessionId;
  await next();
}
// 添加MD5校验
export async function md5Validate(ctx, next) {
  let requestParams = {};
  if (ctx.method === 'GET') {
    requestParams = ctx.request.query;
  } else {
    requestParams = ctx.request.body;
  }
  const { carry, ...rest } = requestParams;
  const notManagePlatform = !/\/apimanage/.test(ctx.url);
  if (blankUrl.find(item => ctx.path.includes(item))) {
    if (ctx.method === 'GET') {
      ctx.request.query = rest;
    } else {
      ctx.request.body = rest;
    }
    await next();
    return;
  } else if (carry && notManagePlatform) {
    let md5Compare;
    if (/^(\/mp)/.test(ctx.url)) {
      // 小程序端的MD5验证
      md5Compare = mpMD5.hexMD5(queryToString(rest) + config.md5_disturb);
    } else {
      md5Compare = md5(queryToString(rest) + config.md5_disturb);
    }
    if (md5Compare !== carry) {
      return (ctx.body = {
        code: 120,
        message: '网关错误',
      });
    }
    if (ctx.method === 'GET') {
      ctx.request.query = rest;
    } else {
      ctx.request.body = rest;
    }
  } else if (!blankUrl.find(item => ctx.path.includes(item)) && notManagePlatform) {
    return (ctx.body = {
      code: 120,
      message: '网关错误',
    });
  }
  await next();
}

// 移除get请求中的timestamp
export async function removeTimestamp(ctx, next) {
  const query = ctx.request.query;
  if (ctx.method === 'GET' && !ctx.url.includes('xkdata-web/wechatNotify')) {
    delete query.timestamp;
  }
  ctx.request.query = query;
  await next();
}
export function queryToString(args) {
  var keys = Object.keys(args);
  keys = keys.sort();
  var newArgs = {};
  keys.forEach(function(key) {
    let k = key.replace(/(\[\])$/, '');
    newArgs[k] = args[key];
  });
  let str = '?';
  for (let k in newArgs) {
    if (newArgs[k] !== null && newArgs[k] !== undefined) {
      str += k + '=' + newArgs[k] + '&';
    }
  }
  str = str.slice(0, -1);
  return str;
}
// 获取get或者post的请求参数并统一保存
export async function getRequestParams(ctx, next) {
  let requestParams = {};
  if (ctx.method === 'GET') {
    if (ctx.request.query.offset) {
      ctx.request.query.offset = parseInt(ctx.request.query.offset);
    }
    if (ctx.request.query.limit) {
      ctx.request.query.limit = parseInt(ctx.request.query.limit);
    }
    if (ctx.request.query.appAccountId) {
      ctx.request.query.appAccountId = parseInt(ctx.request.query.appAccountId);
    }
    requestParams = ctx.request.query;
  } else {
    requestParams = ctx.request.body;
  }
  ctx.requestParams = requestParams || {};
  await next();
}

// 设置sesssionId到请求参数中（使用在manage运营端）
export async function setSessionIdToRequestParams(ctx, next) {
  ctx.requestParams = {
    ...ctx.requestParams,
    // sessionId: ctx.sessionId,
  };
  await next();
}

// 有些接口不要sessionid
export async function removeSessionId(ctx, next) {
  // delete ctx.requestParams.sessionId;
  ctx.requestParams = {
    ...ctx.requestParams,
  };
  await next();
}
